<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Log;
use App\Website;
use App\MailLog;
use App\MonitoringRecord;
use App\Mail\WebsiteError;
use Illuminate\Support\Facades\Mail;
use Carbon\Carbon;

class Monitor extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'monitor:start';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $urls = Website::where('status', 1)->pluck('url', 'id');
        $res = $this->curlm($urls);
        try {
            foreach ($res as $key => $value) {
                if ($value['http_code'] != 200 && $value['http_code'] != 302) {
                    $website = Website::findOrFail($value['website_id']);
                    // $count = $website->monitoringRecords()->whereDate('created_at', Carbon::now()->format('Y-m-d'))->where('status_code', '!=', 200)->count();
                    $last = $website->monitoringRecords()->latest()->first();
                    $mail_log = $website->mailLogs()->whereDate('created_at', Carbon::now()->format('Y-m-d'))->count();
                    if ($last && $last['http_code'] != 200 && $last['http_code'] != 302 && $mail_log < 3) {
                        $result = Mail::to($website->user)->send(new WebsiteError($last));
                        MailLog::create([
                            'website_id' => $website['id']
                        ]);
                    }
                }
            }
        } catch (\Exception $e) {
            #
        }
        MonitoringRecord::insert($res);
    }

    public function curlm($urls)
    {
        $res=[];
        $mh = curl_multi_init();
        foreach ($urls as $i => $url) {
            $conn[$i]=curl_init($url);
            curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($conn[$i], CURLOPT_ENCODING, 'gzip');
            curl_multi_add_handle($mh, $conn[$i]);
        }
        do {
            do {
                $mrc = curl_multi_exec($mh, $active);
            } while ($mrc == CURLM_CALL_MULTI_PERFORM);
            while ($active and $mrc == CURLM_OK) {
                if (curl_multi_select($mh) != -1) {
                    do {
                        $mrc = curl_multi_exec($mh, $active);
                    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
                }
            }
        } while ($active);
        foreach ($urls as $i => $url) {
            $info = curl_getinfo($conn[$i]);
            $item['status_code'] = $info['http_code'];
            $item['http_code'] = $info['http_code'];
            $item['total_time'] = $info['total_time'];
            $item['namelookup_time'] = $info['namelookup_time'];
            $item['connect_time'] = $info['connect_time'];
            $item['pretransfer_time'] = $info['pretransfer_time'];
            $item['starttransfer_time'] = $info['starttransfer_time'];
            $item['redirect_time'] = $info['redirect_time'];
            $item['created_at'] = Carbon::now();
            $item['website_id'] = $i;
            $res[$i]=$item;
            curl_close($conn[$i]);
        }

        return $res;
    }
}
